//
//  TimerTableViewController.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/10/25.
//

import UIKit
import CoreData

class TimerTableViewController: BaseTableViewController {
    
    private var fetchedRC: NSFetchedResultsController<CustomTimer>!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "计时器"
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.addTimer))
        
        tableView.rowHeight = 70
        tableView.separatorStyle = .none
        tableView.register(UINib(nibName: kTimerCell, bundle: nil), forCellReuseIdentifier: kTimerCell)
        
        fetchedRC = CustomTimerStore.query()
        fetchedRC.delegate = self
    }
    
    @objc private func addTimer() {
//        navigationController?.pushViewController(TimerAddViewController(style: .grouped), animated: true)
        navigationController?.pushViewController(TimerAddViewController(), animated: true)
    }

}

extension TimerTableViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fetchedRC.fetchedObjects?.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: kTimerCell, for: indexPath) as! TimerCell
        let timer = fetchedRC.object(at: indexPath)
        cell.timer = timer
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        super.tableView(tableView, didSelectRowAt: indexPath)
        
        let timer = fetchedRC.object(at: indexPath)
        let timingVc = TimingViewController()
        timingVc.customTimer = timer
        navigationController?.pushViewController(timingVc, animated: true)
    }
    
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let test = UIContextualAction(style: .normal, title: "编辑") { (action, view, completion) in
            let vc = TimerAddViewController()
            vc.customTimer = self.fetchedRC.object(at: indexPath)
            self.navigationController?.pushViewController(vc, animated: true)
            completion(false)
        }
            
        let config = UISwipeActionsConfiguration(actions: [test])
        config.performsFirstActionWithFullSwipe = false
        return config
    }
}

extension TimerTableViewController: NSFetchedResultsControllerDelegate {
    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        self.tableView.beginUpdates()
    }
    
    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch type {
        case .insert:
            tableView.insertRows(at: [newIndexPath!], with: .automatic)
        case .delete:
            tableView.deleteRows(at: [indexPath!], with: .automatic)
        case .update:
            let cell = tableView.cellForRow(at: indexPath!) as! TimerCell
            let timer = fetchedRC.object(at: indexPath!)
            cell.timer = timer
        case .move:
            tableView.deleteRows(at: [indexPath!], with: .automatic)
            tableView.insertRows(at: [newIndexPath!], with: .automatic)
        @unknown default: break
        }
    }
        
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.endUpdates()
    }
}
